package com.doubao.auth.service;

import com.doubao.auth.client.JumdataSmsClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@RequiredArgsConstructor
public class VerificationCodeService {

    private final JumdataSmsClient smsClient;
    private final RedisTemplate<String, String> redisTemplate;

    // Redis Key前缀
    private static final String CODE_KEY_PREFIX = "sms:code:";
    // 验证码有效期（分钟）
    private static final int CODE_EXPIRE = 5;
    // 验证码长度
    private static final int CODE_LENGTH = 6;

    /**
     * 生成并发送验证码
     * @param phoneNumber 手机号
     * @return 是否发送成功
     */
    public boolean sendCode(String phoneNumber) {
        // 生成随机验证码
        String code = generateRandomCode(CODE_LENGTH);

        // 存储验证码到Redis
        redisTemplate.opsForValue().set(
                CODE_KEY_PREFIX + phoneNumber,
                code,
                CODE_EXPIRE,
                TimeUnit.MINUTES
        );

        // 发送验证码短信
        boolean sendResult = smsClient.sendVerificationCode(phoneNumber, code);
        if (!sendResult) {
            // 如果发送失败，删除Redis中的验证码
            redisTemplate.delete(CODE_KEY_PREFIX + phoneNumber);
        }

        return sendResult;
    }

    /**
     * 校验验证码
     * @param phoneNumber 手机号
     * @param code 验证码
     * @return 是否验证通过
     */
    public boolean verifyCode(String phoneNumber, String code) {
        String key = CODE_KEY_PREFIX + phoneNumber;
        String storedCode = redisTemplate.opsForValue().get(key);

        if (storedCode != null && storedCode.equals(code)) {
            // 验证成功后删除验证码
            redisTemplate.delete(key);
            return true;
        }

        return false;
    }

    /**
     * 生成随机验证码
     * @param length 验证码长度
     * @return 随机验证码
     */
    private String generateRandomCode(int length) {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }
}